package com.mqz.zebraEcommerce.commodity.exception;

import com.mqz.zebraEcommerce.common.exception.CodeEnum;
import com.mqz.zebraEcommerce.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestControllerAdvice(basePackages = "com.mqz.zebraEcommerce.commodity.controller;")
public class ExceptionControllerAdvice {

    //处理数据验证异常
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public R handleValidException(MethodArgumentNotValidException e) {
        BindingResult result = e.getBindingResult();
        Map<String, String> errorMap = new HashMap<>();
        result.getFieldErrors().forEach(fieldError -> {
            errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
        });
        return R.error(CodeEnum.INVALID_EXCEPTION.getCode(), CodeEnum.INVALID_EXCEPTION.getMsg()).put("data", errorMap);
    }

    //处理其他异常
    @ExceptionHandler({Throwable.class})
    public R handleException() {
        return R.error(CodeEnum.UNKNOWN_EXCEPTION.getCode(), CodeEnum.UNKNOWN_EXCEPTION.getMsg());
    }
}
